﻿using DL.Core.ulitity.tools;
using DL.Core.ulitity.ui;
using DL.Core.ulitity.web;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace DL.Core.Swagger
{
    /// <summary>
    /// 中间件
    /// </summary>
    public interface IHttpMiddleware
    {
        Task Invoke(HttpContext HttpContext);
    }
    public class ExceptionMiddlerware:IHttpMiddleware
    {
        private readonly RequestDelegate _next;
        public ExceptionMiddlerware(RequestDelegate request)
        {
            _next = request;
        }

        public async Task Invoke(HttpContext HttpContext)
        {
            try
            {
                await _next(HttpContext);
            }
            catch (Exception ex)
            {
                var result = new ReturnResult(ReturnResultCode.Failed, null, ex.Message ?? ex.InnerException.Message);
                var json = result.ToJson();
                HttpContext.Response.ContentType = HttpType.JsonType;
                await HttpContext.Response.WriteAsync(json);  
            }
        }
    }
}
